#region License

// Copyright (c) 2006-2008, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice, 
//      this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, 
//      this list of conditions and the following disclaimer in the documentation 
//      and/or other materials provided with the distribution.
//    * Neither the name of ClearCanvas Inc. nor the names of its contributors 
//      may be used to endorse or promote products derived from this software without 
//      specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
// OF SUCH DAMAGE.

#endregion

using System;
using System.Collections.Generic;
using System.Text;

using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Tools;
using ClearCanvas.Desktop.Actions;
using ClearCanvas.ImageViewer.Configuration;
using ClearCanvas.ImageViewer.StudyManagement;
using ClearCanvas.ImageViewer.Explorer.Dicom;
using ClearCanvas.Dicom.DataStore;
using ClearCanvas.Dicom;

namespace WriteCDPlugin
{
    // This template provides the boiler-plate code for creating a basic tool
    // that performs a single action when its menu item or toolbar button is clicked.

    // Declares a menu action with action ID "activate"
    // TODO: Change the action path hint to your desired menu path, or
    // remove this attribute if you do not want to create a menu item for this tool
    [MenuAction("activate", "dicomstudybrowser-contextmenu/MenuWriteCD", "WriteCD")]

    // Declares a toolbar button action with action ID "activate"
    // TODO: Change the action path hint to your desired toolbar path, or
    // remove this attribute if you do not want to create a toolbar button for this tool
    [ButtonAction("activate", "dicomstudybrowser-toolbar/ToolbarWriteCD", "WriteCD")]

    // Specifies tooltip text for the "activate" action
    // TODO: Replace tooltip text
    [Tooltip("activate", "TooltipWriteCD")]

    // Specifies icon resources to use for the "activate" action
    // TODO: Replace the icon resource names with your desired icon resources
    [IconSet("activate", IconScheme.Colour, "Icons.WriteCDToolSmall.png", "Icons.WriteCDToolMedium.png", "Icons.WriteCDToolLarge.png")]

    // Specifies that the enablement of the "activate" action in the user-interface
    // is controlled by observing a boolean property named "Enabled", listening to
    // an event named "EnabledChanged" for changes to this property
    [EnabledStateObserver("activate", "Enabled", "EnabledChanged")]

    [ExtensionOf(typeof(StudyBrowserToolExtensionPoint))]
    public class WriteCDTool : StudyBrowserTool
    {

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <remarks>
        /// A no-args constructor is required by the framework.  Do not remove.
        /// </remarks>
        public WriteCDTool()
        {
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        private void WriteCD()
        {
            BlockingOperation.Run(this.WriteCDInternal);
        }

        private void WriteCDInternal()
        {
            if (this.Context.SelectedStudies == null)
                return;

            if (this.Context.SelectedStudies.Count == 1)
            {
                WriteSingleStudyCD();
            }
            else
            {
                WriteMultipleStudiesCD();
            }
        }

        private void WriteSingleStudyCD()
        {
            StudyItem item = this.Context.SelectedStudy;
            String studyInstanceUid = item.StudyInstanceUID;
            List<String> files = GetStudyFiles(studyInstanceUid);
            if (files.Count>0)
                ShowWriteCDForm(files);
        }

        private void ShowWriteCDForm(List<String> files)
        {
            WriteCDForm writeCDForm = new WriteCDForm();
            writeCDForm.ShowDialog();
        }

        private List<String> GetStudyFiles(String studyInstanceUid)
        {
            List<String> files = new List<String>();
            List<ISopInstance> sops = null;
            IStudy study = null;
            using (IDataStoreReader reader = DataAccessLayer.GetIDataStoreReader())
            {
                study = reader.GetStudy(new Uid(studyInstanceUid));
                sops = new List<ISopInstance>(study.GetSopInstances());
                foreach (ImageSopInstance imageObject in sops)
                {
                    files.Add(imageObject.LocationUri.LocalDiskPath);
                }
            }
            return files;
        }

        private void WriteMultipleStudiesCD()
        {
            List<String> files = new List<String>();
            String studyInstanceUid = null;
            foreach (StudyItem item in this.Context.SelectedStudies)
            {
                studyInstanceUid = item.StudyInstanceUID;
                files.AddRange(GetStudyFiles(studyInstanceUid));
            }
            if (files.Count > 0)
                ShowWriteCDForm(files);
        }

        protected override void OnSelectedStudyChanged(object sender, EventArgs e)
        {
            // If the results aren't from the local machine, then we don't
            // even care whether a study has been selected or not
            if (!this.Context.SelectedServerGroup.IsLocalDatastore)
                return;

            base.OnSelectedStudyChanged(sender, e);
        }

        protected override void OnSelectedServerChanged(object sender, EventArgs e)
        {
            if (this.Context.SelectedServerGroup.IsLocalDatastore)
            {
                if (this.Context.SelectedStudy != null)
                    this.Enabled = true;
                else
                    this.Enabled = false;
            }
            else
            {
                this.Enabled = false;
            }
        }
    }
}
